from wtforms import StringField, IntegerField
from wtforms.validators import DataRequired, length, Email, Regexp
from wtforms import ValidationError
from app.libs.enums import ClientTypeEnum
from app.validates.base import BaseForm as Form
from app.models.user import User


class ClientForm(Form):
    openid = StringField(validators=[DataRequired(message='不允许为空'), length(
        min=5, max=32
    )])
    nicename = StringField()
    type = IntegerField(validators=[DataRequired()])
    code = StringField(validators=[DataRequired(message='code  不允许为空'), length(
        min=5, max=32
    )])

    def validate_type(self, value):
        try:
            client = ClientTypeEnum(value.data)
        except ValueError as e:
            raise e
        self.type.data = client


# # 验证小程序端 登录传过来的code
#
# class CodeForm(Form):
#     code = StringField(validators=[DataRequired(message='code  不允许为空'), length(
#         min=5, max=32
#     )])


class UserOpenidForm(ClientForm):
    # account = StringField(validators=[
    #     Email(message='invalidate openid')
    # ])
    # secret = StringField(validators=[
    #     DataRequired(),
    #     # password can only include letters , numbers and "_"
    #     Regexp(r'^[A-Za-z0-9_*&$#@]{6,22}$')
    # ])
    nickname = StringField(validators=[DataRequired(),
                                       length(min=2, max=22)])
    openid = StringField(validators=[DataRequired(),
                                       length(min=10, max=33)])
    avarat = StringField(validators=[DataRequired(),
                                       length(min=50, max=122)])

    def validate_openid(self, value):
        if User.query.filter_by(openid=value.data).first():
            raise ValidationError()

class BookSearchForm(Form):
    q = StringField(validators=[DataRequired()])


class TokenForm(Form):
    token = StringField(validators=[DataRequired()])
class CodeForm(Form):
    code = StringField(validators=[DataRequired(message='code不允许为空'), length(
        min=5, max=32
    )])
